<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>课程详情</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="goBack">返回</el-button>
      </div>
      <el-descriptions class="margin-top" title="基本信息" :column="2" border>
        <el-descriptions-item label="课程名称">{{ courseInfo.name }}</el-descriptions-item>
        <el-descriptions-item label="课程类型">{{ getTypeText(courseInfo.type) }}</el-descriptions-item>
        <el-descriptions-item label="讲师">{{ courseInfo.instructor }}</el-descriptions-item>
        <el-descriptions-item label="课时">{{ courseInfo.duration }}小时</el-descriptions-item>
        <el-descriptions-item label="课程状态">
          <el-tag :type="courseInfo.status | statusFilter">{{ courseInfo.status | statusTextFilter }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="课程描述">{{ courseInfo.description }}</el-descriptions-item>
      </el-descriptions>

      <div class="schedule-section">
        <div class="section-header">
          <h3>课程安排</h3>
          <el-button type="primary" size="small" @click="handleAddSchedule">添加课程安排</el-button>
        </div>
        <el-table :data="schedules" border style="width: 100%">
          <el-table-column prop="date" label="上课日期" align="center">
            <template slot-scope="{row}">
              {{ row.date | parseTime('{y}-{m}-{d}') }}
            </template>
          </el-table-column>
          <el-table-column prop="startTime" label="开始时间" align="center" />
          <el-table-column prop="endTime" label="结束时间" align="center" />
          <el-table-column prop="location" label="上课地点" align="center" />
          <el-table-column label="操作" align="center" width="150">
            <template slot-scope="{row}">
              <el-button type="danger" size="mini" @click="handleDeleteSchedule(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="materials-section">
        <div class="section-header">
          <h3>课程资料</h3>
          <el-button type="primary" size="small" @click="handleUpload">上传资料</el-button>
        </div>
        <el-table :data="materials" border style="width: 100%">
          <el-table-column prop="name" label="文件名" align="center" />
          <el-table-column prop="size" label="大小" align="center">
            <template slot-scope="{row}">
              {{ formatFileSize(row.size) }}
            </template>
          </el-table-column>
          <el-table-column prop="uploadTime" label="上传时间" align="center">
            <template slot-scope="{row}">
              {{ row.uploadTime | parseTime('{y}-{m}-{d}') }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="200">
            <template slot-scope="{row}">
              <el-button type="text" @click="handleDownload(row)">下载</el-button>
              <el-button type="text" class="delete-button" @click="handleDeleteMaterial(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 添加课程安排对话框 -->
    <el-dialog title="添加课程安排" :visible.sync="scheduleDialogVisible" width="40%">
      <el-form ref="scheduleForm" :model="scheduleForm" :rules="scheduleRules" label-width="100px">
        <el-form-item label="上课日期" prop="date">
          <el-date-picker
            v-model="scheduleForm.date"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item label="上课时间" required>
          <el-col :span="11">
            <el-form-item prop="startTime">
              <el-time-picker
                v-model="scheduleForm.startTime"
                placeholder="开始时间"
                format="HH:mm"
                value-format="HH:mm"
              />
            </el-form-item>
          </el-col>
          <el-col class="line" :span="2">-</el-col>
          <el-col :span="11">
            <el-form-item prop="endTime">
              <el-time-picker
                v-model="scheduleForm.endTime"
                placeholder="结束时间"
                format="HH:mm"
                value-format="HH:mm"
              />
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="上课地点" prop="location">
          <el-input v-model="scheduleForm.location" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="scheduleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAddSchedule">确定</el-button>
      </div>
    </el-dialog>

    <!-- 上传资料对话框 -->
    <el-dialog title="上传课程资料" :visible.sync="uploadDialogVisible" width="30%">
      <el-upload
        class="upload-demo"
        :action="uploadUrl"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :before-upload="beforeUpload"
      >
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传pdf/doc/docx/ppt文件</div>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script>
import { getCourseDetail, addSchedule, deleteSchedule, uploadMaterial, deleteMaterial } from '@/api/training'

export default {
  name: 'TrainingCourseDetail',
  filters: {
    statusFilter(status) {
      const statusMap = {
        'NOT_STARTED': 'info',
        'IN_PROGRESS': 'success',
        'COMPLETED': 'warning',
        'CANCELLED': 'danger'
      }
      return statusMap[status]
    },
    statusTextFilter(status) {
      const statusMap = {
        'NOT_STARTED': '未开始',
        'IN_PROGRESS': '进行中',
        'COMPLETED': '已完成',
        'CANCELLED': '已取消'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      courseInfo: {},
      schedules: [],
      materials: [],
      scheduleDialogVisible: false,
      uploadDialogVisible: false,
      scheduleForm: {
        date: '',
        startTime: '',
        endTime: '',
        location: ''
      },
      scheduleRules: {
        date: [{ required: true, message: '请选择上课日期', trigger: 'change' }],
        startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
        endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
        location: [{ required: true, message: '请输入上课地点', trigger: 'blur' }]
      },
      uploadUrl: process.env.VUE_APP_BASE_API + '/training/material/upload'
    }
  },
  created() {
    this.getCourseInfo()
  },
  methods: {
    getCourseInfo() {
      const id = this.$route.params.id
      getCourseDetail(id).then(response => {
        this.courseInfo = response.data
        this.schedules = response.data.schedules || []
        this.materials = response.data.materials || []
      })
    },
    getTypeText(type) {
      const typeMap = {
        'TECHNICAL': '技术课程',
        'MANAGEMENT': '管理课程',
        'GENERAL': '通用课程'
      }
      return typeMap[type] || type
    },
    formatFileSize(size) {
      if (size < 1024) return size + 'B'
      if (size < 1024 * 1024) return (size / 1024).toFixed(2) + 'KB'
      return (size / (1024 * 1024)).toFixed(2) + 'MB'
    },
    handleAddSchedule() {
      this.scheduleForm = {
        date: '',
        startTime: '',
        endTime: '',
        location: ''
      }
      this.scheduleDialogVisible = true
    },
    confirmAddSchedule() {
      this.$refs.scheduleForm.validate(valid => {
        if (valid) {
          addSchedule({
            courseId: this.courseInfo.id,
            ...this.scheduleForm
          }).then(() => {
            this.$message.success('添加成功')
            this.scheduleDialogVisible = false
            this.getCourseInfo()
          })
        }
      })
    },
    handleDeleteSchedule(row) {
      this.$confirm('确认删除该课程安排吗？', '提示', {
        type: 'warning'
      }).then(() => {
        deleteSchedule(row.id).then(() => {
          this.$message.success('删除成功')
          this.getCourseInfo()
        })
      })
    },
    handleUpload() {
      this.uploadDialogVisible = true
    },
    beforeUpload(file) {
      const validTypes = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.ms-powerpoint']
      if (!validTypes.includes(file.type)) {
        this.$message.error('只能上传PDF/DOC/DOCX/PPT格式文件！')
        return false
      }
      return true
    },
    handleUploadSuccess() {
      this.$message.success('上传成功')
      this.uploadDialogVisible = false
      this.getCourseInfo()
    },
    handleUploadError() {
      this.$message.error('上传失败')
    },
    handleDownload(row) {
      window.open(row.url)
    },
    handleDeleteMaterial(row) {
      this.$confirm('确认删除该课程资料吗？', '提示', {
        type: 'warning'
      }).then(() => {
        deleteMaterial(row.id).then(() => {
          this.$message.success('删除成功')
          this.getCourseInfo()
        })
      })
    },
    goBack() {
      this.$router.push('/hr/training/course')
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 20px 0;

    h3 {
      margin: 0;
    }
  }

  .schedule-section,
  .materials-section {
    margin-top: 30px;
  }

  .delete-button {
    color: #f56c6c;
  }

  .line {
    text-align: center;
    line-height: 36px;
  }
}
</style>